package com.ztsoft.user.service.project.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ztsoft.user.mapper.project.ContactsMapper;
import com.ztsoft.user.pojo.entity.project.Contacts;
import com.ztsoft.user.pojo.vo.project.UnifiedForms;
import com.ztsoft.user.service.project.ContactsService;
import com.ztsoft.user.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Objects;

@Slf4j
@Service
public class ContactsServiceImpl extends ServiceImpl<ContactsMapper, Contacts> implements ContactsService {

    @Override
    public Result<Object> updateContacts(Contacts contacts) {
        boolean isSuccess = this.updateById(contacts);
        if (isSuccess) {
            return Result.success();
        }
        return Result.fail();
    }

    @Override
    public Result<Object> addContacts(Contacts contacts) {
        boolean isSuccess = this.save(contacts);
        if (isSuccess) {
            return Result.success();
        }
        return Result.fail();
    }

    @Override
    public Result<Object> deleteContacts(String id) {
        boolean isSuccess = this.removeById(id);
        if (isSuccess) {
            return Result.success();
        }
        return Result.fail();
    }

    @Override
    public Result<Object> getContactsByDemandUnitId(String pDemandUnitId) {
        QueryWrapper<Contacts> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("demand_unit_id", pDemandUnitId);
        return Result.success(this.list(queryWrapper));
    }

    @Override
    public Result<Object> unified(UnifiedForms<Contacts> unifiedForms) {
        try {
            Contacts[] insertRecords = unifiedForms.getInsertRecords();
            Contacts[] removeRecords = unifiedForms.getRemoveRecords();
            Contacts[] updateRecords = unifiedForms.getUpdateRecords();

            if (Objects.nonNull(insertRecords) && insertRecords.length != 0) {
                this.saveBatch(Arrays.asList(insertRecords));
            }
            if (Objects.nonNull(removeRecords) && removeRecords.length != 0) {
                for (Contacts removeRecord : removeRecords) {
                    this.removeById(removeRecord.getId());
                }
            }
            if (Objects.nonNull(updateRecords) && updateRecords.length != 0) {
                this.updateBatchById(Arrays.asList(updateRecords));
            }
            return Result.success();
        } catch (Exception e) {
            log.info("出现异常", e);
            return Result.error();
        }
    }
}
